import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { 
  ShoppingCart, 
  Heart, 
  Share2, 
  Star, 
  Truck, 
  Shield, 
  RotateCcw,
  Plus,
  Minus
} from 'lucide-react';
import { productApi, cartApi } from '@/db/api';
import { useAuth } from 'miaoda-auth-react';
import type { Product } from '@/types/types';
import { toast } from 'sonner';

const ProductDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { user } = useAuth();
  
  const [product, setProduct] = useState<Product | null>(null);
  const [loading, setLoading] = useState(true);
  const [selectedImage, setSelectedImage] = useState(0);
  const [selectedSize, setSelectedSize] = useState('');
  const [selectedColor, setSelectedColor] = useState('');
  const [quantity, setQuantity] = useState(1);
  const [addingToCart, setAddingToCart] = useState(false);

  useEffect(() => {
    if (id) {
      loadProduct();
    }
  }, [id]);

  const loadProduct = async () => {
    try {
      setLoading(true);
      const data = await productApi.getProduct(id!);
      if (data) {
        setProduct(data);
        // 设置默认选项
        if (data.sizes && data.sizes.length > 0) {
          setSelectedSize(data.sizes[0]);
        }
        if (data.colors && data.colors.length > 0) {
          setSelectedColor(data.colors[0]);
        }
      } else {
        toast.error('商品不存在');
        navigate('/products');
      }
    } catch (error) {
      console.error('加载商品失败:', error);
      toast.error('加载商品失败');
      navigate('/products');
    } finally {
      setLoading(false);
    }
  };

  const handleAddToCart = async () => {
    if (!user) {
      toast.error('请先登录');
      navigate('/login');
      return;
    }

    if (!product) return;

    try {
      setAddingToCart(true);
      await cartApi.addToCart({
        product_id: product.id,
        quantity,
        size: selectedSize || undefined,
        color: selectedColor || undefined
      });
      toast.success('已添加到购物车');
    } catch (error) {
      console.error('添加到购物车失败:', error);
      toast.error('添加到购物车失败');
    } finally {
      setAddingToCart(false);
    }
  };

  const handleBuyNow = async () => {
    if (!user) {
      toast.error('请先登录');
      navigate('/login');
      return;
    }

    await handleAddToCart();
    navigate('/cart');
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-pink-600"></div>
      </div>
    );
  }

  if (!product) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <h2 className="text-2xl font-bold text-gray-900 mb-4">商品不存在</h2>
          <Button onClick={() => navigate('/products')}>返回商品列表</Button>
        </div>
      </div>
    );
  }

  const images = product.images && product.images.length > 0 
    ? product.images 
    : ['https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=800'];

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-12">
          {/* Product Images */}
          <div className="space-y-4">
            <div className="aspect-square overflow-hidden rounded-lg bg-white">
              <img
                src={images[selectedImage]}
                alt={product.name}
                className="w-full h-full object-cover"
              />
            </div>
            
            {images.length > 1 && (
              <div className="grid grid-cols-4 gap-4">
                {images.map((image, index) => (
                  <button
                    key={index}
                    onClick={() => setSelectedImage(index)}
                    className={`aspect-square overflow-hidden rounded-lg border-2 transition-colors ${
                      selectedImage === index
                        ? 'border-pink-600'
                        : 'border-gray-200 hover:border-gray-300'
                    }`}
                  >
                    <img
                      src={image}
                      alt={`${product.name} ${index + 1}`}
                      className="w-full h-full object-cover"
                    />
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Product Info */}
          <div className="space-y-6">
            <div>
              <div className="flex items-center gap-2 mb-2">
                <h1 className="text-3xl font-bold text-gray-900">{product.name}</h1>
                {product.is_featured && (
                  <Badge className="bg-pink-100 text-pink-800">推荐</Badge>
                )}
              </div>
              
              <div className="flex items-center gap-4 mb-4">
                <div className="flex items-center">
                  {[...Array(5)].map((_, i) => (
                    <Star
                      key={i}
                      className={`h-5 w-5 ${
                        i < 4 ? 'text-yellow-400 fill-current' : 'text-gray-300'
                      }`}
                    />
                  ))}
                  <span className="ml-2 text-sm text-gray-600">(128 评价)</span>
                </div>
                <span className="text-sm text-gray-500">
                  分类: {product.category?.name}
                </span>
              </div>

              <div className="flex items-center gap-4 mb-6">
                <span className="text-3xl font-bold text-pink-600">
                  ¥{product.price}
                </span>
                {product.original_price && (
                  <span className="text-xl text-gray-500 line-through">
                    ¥{product.original_price}
                  </span>
                )}
                {product.original_price && (
                  <Badge variant="destructive">
                    省 ¥{(product.original_price - product.price).toFixed(2)}
                  </Badge>
                )}
              </div>

              <p className="text-gray-600 leading-relaxed">
                {product.description}
              </p>
            </div>

            <Separator />

            {/* Product Options */}
            <div className="space-y-4">
              {/* Size Selection */}
              {product.sizes && product.sizes.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    尺码
                  </label>
                  <Select value={selectedSize} onValueChange={setSelectedSize}>
                    <SelectTrigger className="w-full">
                      <SelectValue placeholder="选择尺码" />
                    </SelectTrigger>
                    <SelectContent>
                      {product.sizes.map((size) => (
                        <SelectItem key={size} value={size}>
                          {size}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* Color Selection */}
              {product.colors && product.colors.length > 0 && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    颜色
                  </label>
                  <Select value={selectedColor} onValueChange={setSelectedColor}>
                    <SelectTrigger className="w-full">
                      <SelectValue placeholder="选择颜色" />
                    </SelectTrigger>
                    <SelectContent>
                      {product.colors.map((color) => (
                        <SelectItem key={color} value={color}>
                          {color}
                        </SelectItem>
                      ))}
                    </SelectContent>
                  </Select>
                </div>
              )}

              {/* Quantity Selection */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  数量
                </label>
                <div className="flex items-center gap-3">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setQuantity(Math.max(1, quantity - 1))}
                    disabled={quantity <= 1}
                  >
                    <Minus className="h-4 w-4" />
                  </Button>
                  <span className="w-12 text-center font-medium">{quantity}</span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setQuantity(Math.min(product.stock, quantity + 1))}
                    disabled={quantity >= product.stock}
                  >
                    <Plus className="h-4 w-4" />
                  </Button>
                  <span className="text-sm text-gray-500 ml-4">
                    库存: {product.stock}
                  </span>
                </div>
              </div>
            </div>

            <Separator />

            {/* Action Buttons */}
            <div className="space-y-4">
              <div className="flex gap-4">
                <Button
                  onClick={handleAddToCart}
                  disabled={addingToCart || product.stock === 0}
                  className="flex-1"
                  variant="outline"
                >
                  <ShoppingCart className="h-5 w-5 mr-2" />
                  {addingToCart ? '添加中...' : '加入购物车'}
                </Button>
                <Button
                  onClick={handleBuyNow}
                  disabled={addingToCart || product.stock === 0}
                  className="flex-1 bg-pink-600 hover:bg-pink-700"
                >
                  立即购买
                </Button>
              </div>

              <div className="flex gap-4">
                <Button variant="ghost" size="sm" className="flex-1">
                  <Heart className="h-4 w-4 mr-2" />
                  收藏
                </Button>
                <Button variant="ghost" size="sm" className="flex-1">
                  <Share2 className="h-4 w-4 mr-2" />
                  分享
                </Button>
              </div>
            </div>

            <Separator />

            {/* Service Info */}
            <div className="space-y-4">
              <h3 className="font-semibold text-gray-900">服务保障</h3>
              <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
                <div className="flex items-center gap-3">
                  <div className="bg-green-100 rounded-full p-2">
                    <Truck className="h-5 w-5 text-green-600" />
                  </div>
                  <div>
                    <div className="font-medium text-sm">包邮配送</div>
                    <div className="text-xs text-gray-500">48小时发货</div>
                  </div>
                </div>
                
                <div className="flex items-center gap-3">
                  <div className="bg-blue-100 rounded-full p-2">
                    <Shield className="h-5 w-5 text-blue-600" />
                  </div>
                  <div>
                    <div className="font-medium text-sm">品质保证</div>
                    <div className="text-xs text-gray-500">正品保障</div>
                  </div>
                </div>
                
                <div className="flex items-center gap-3">
                  <div className="bg-orange-100 rounded-full p-2">
                    <RotateCcw className="h-5 w-5 text-orange-600" />
                  </div>
                  <div>
                    <div className="font-medium text-sm">7天退换</div>
                    <div className="text-xs text-gray-500">无理由退换</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        {/* Product Details */}
        <div className="mt-16">
          <Card>
            <CardContent className="p-8">
              <h2 className="text-2xl font-bold text-gray-900 mb-6">商品详情</h2>
              <div className="prose max-w-none">
                <p className="text-gray-600 leading-relaxed">
                  {product.description || '暂无详细描述'}
                </p>
                
                <div className="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8">
                  <div>
                    <h3 className="text-lg font-semibold mb-4">商品信息</h3>
                    <dl className="space-y-2">
                      <div className="flex justify-between">
                        <dt className="text-gray-600">商品名称:</dt>
                        <dd className="font-medium">{product.name}</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="text-gray-600">商品分类:</dt>
                        <dd className="font-medium">{product.category?.name}</dd>
                      </div>
                      <div className="flex justify-between">
                        <dt className="text-gray-600">库存数量:</dt>
                        <dd className="font-medium">{product.stock}</dd>
                      </div>
                      {product.sizes && product.sizes.length > 0 && (
                        <div className="flex justify-between">
                          <dt className="text-gray-600">可选尺码:</dt>
                          <dd className="font-medium">{product.sizes.join(', ')}</dd>
                        </div>
                      )}
                      {product.colors && product.colors.length > 0 && (
                        <div className="flex justify-between">
                          <dt className="text-gray-600">可选颜色:</dt>
                          <dd className="font-medium">{product.colors.join(', ')}</dd>
                        </div>
                      )}
                    </dl>
                  </div>
                  
                  <div>
                    <h3 className="text-lg font-semibold mb-4">购买须知</h3>
                    <ul className="space-y-2 text-gray-600">
                      <li>• 商品图片仅供参考，以实物为准</li>
                      <li>• 支持7天无理由退换货</li>
                      <li>• 全国包邮，48小时内发货</li>
                      <li>• 如有质量问题，支持免费退换</li>
                      <li>• 客服热线：400-888-8888</li>
                    </ul>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
};

export default ProductDetail;